package com.github.baichuan.iot.gateway.handler;

import com.github.baichuan.iot.protocol.codec.MessageEncodeContext;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import lombok.NonNull;

import java.util.function.Consumer;

/**
 * 出站消息消费处理器
 * 用于实现对出站消息的处理，如将出站报文写入外部存储
 */
@ChannelHandler.Sharable
public class OutboundConsumeHandler extends ChannelOutboundHandlerAdapter {
    private Consumer<MessageEncodeContext> consumer;

    public OutboundConsumeHandler(@NonNull Consumer<MessageEncodeContext> consumer){
        this.consumer = consumer;
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if(msg instanceof MessageEncodeContext){
            MessageEncodeContext outbound = (MessageEncodeContext) msg;
            consumer.accept(outbound);
        }

        super.write(ctx, msg, promise);
    }
}
